﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Mono.Cecil;
using TK_CSLua.ILAnalyze;

namespace CSLua
{
	// Token: 0x0200000E RID: 14
	public abstract class AssemblyGenerator
	{
		// Token: 0x06000061 RID: 97 RVA: 0x00003EA2 File Offset: 0x000020A2
		public static void AppendError(string error)
		{
			AssemblyGenerator.errorMsg.Append(error);
		}

		// Token: 0x06000062 RID: 98
		protected abstract TypeGenerator CreateGenerateType(LuaType luaType);

		// Token: 0x06000063 RID: 99 RVA: 0x00003EB0 File Offset: 0x000020B0
		public void GeneratorAssembly(string fileName, string folder)
		{
			LuaAssembly luaAssembly = AssemblyAnalyze.LoadAssembly(fileName, null);
			StringBuilder protoTypes = new StringBuilder();
			protoTypes.Append("if G_CSL_AllTypes == nil then G_CSL_AllTypes = {} end").AppendLine();
			foreach (LuaType luaClass in luaAssembly.LuaTypes)
			{
				this.CreateGenerateType(luaClass).Generate(folder);
				protoTypes.AppendFormat("G_CSL_AllTypes['{0}']=true\n", luaClass.ILTypeDef.luaIdentifier());
			}
			protoTypes.Append("if G_CSL_ProtoEnums == nil then G_CSL_ProtoEnums = {} end").AppendLine();
			new Dictionary<string, string>();
			foreach (TypeDefinition protoType in luaAssembly.ProtoEnumTypes)
			{
				if (protoType.IsEnum)
				{
					protoTypes.AppendLine();
					protoTypes.AppendFormat("G_CSL_ProtoEnums['{0}']=", BuilderUtils.GetTypeFullname(protoType, true)).AppendLine("{");
					foreach (FieldDefinition field in protoType.Fields)
					{
						if (field.IsStatic && field.FieldType.FullName == protoType.FullName)
						{
							protoTypes.AppendFormat("{0}={1},[{1}]='{0}',", field.Name, (int)field.Constant).AppendLine();
						}
					}
					protoTypes.AppendLine("}");
					protoTypes.AppendLine();
				}
				else
				{
					string fullName = BuilderUtils.GetTypeFullname(protoType, true);
					protoTypes.AppendFormat("package.loaded['{0}']=class('{1}')", fullName, fullName);
					protoTypes.AppendLine();
				}
			}
			File.WriteAllText(folder + "/" + luaAssembly.ilAssembly.Name.Name + "_csl_metadata.lua", protoTypes.ToString());
			if (AssemblyGenerator.errorMsg.Length > 0)
			{
				throw new Exception(AssemblyGenerator.errorMsg.ToString());
			}
		}

		// Token: 0x0400002D RID: 45
		private const string csl_metadata = "csl_metadata.lua";

		// Token: 0x0400002E RID: 46
		private static StringBuilder errorMsg = new StringBuilder();
	}
}
